package com.cincc.cinccimdemo.common;

import android.util.Log;

import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class DownloadUtils {

    public static void downloadFile(String url, String saveDir, DownloadCallback downloadCallback) {
        try {
            //下载路径，如果路径无效了，可换成你的下载路径
            final long startTime = System.currentTimeMillis();
            Log.i("DOWNLOAD", "startTime=" + startTime);
            //下载函数
            String filename = url.substring(url.lastIndexOf("/") + 1);
            //获取文件名
            URL myURL = new URL(url);
            URLConnection conn = myURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            int fileSize = conn.getContentLength();//根据响应获取文件大小
            if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
            if (is == null) throw new RuntimeException("stream is null");
            File file1 = new File(saveDir);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            String filePath = saveDir + filename;
            //把数据存入路径+文件名
            FileOutputStream fos = new FileOutputStream(filePath);
            byte buf[] = new byte[1024];
            int downLoadFileSize = 0;
            do {
                //循环读取
                int numread = is.read(buf);
                if (numread == -1) {
                    break;
                }
                fos.write(buf, 0, numread);
                downLoadFileSize += numread;
                downloadCallback.progress(fileSize, downLoadFileSize);
                //更新进度条
            } while (true);

            Log.i("DOWNLOAD", "download success filePath = " + filePath);
            Log.i("DOWNLOAD", "totalTime=" + (System.currentTimeMillis() - startTime));
            downloadCallback.success(filePath);
            is.close();
        } catch (Exception ex) {
            Log.e("DOWNLOAD", "error: " + ex.getMessage(), ex);
            downloadCallback.error(ex.getMessage());
        }
    }

    public interface DownloadCallback {
        void success(String savePath) throws JSONException;

        void error(String msg);

        void progress(int total, int progress);
    }
}
